/**
 * Project Name:fastPlat
 * File Name:AdminUserController.java
 * Package Name:com.fast.cms.web.controller
 * Date:2014年9月15日上午9:43:20
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/
package com.fast.user.web.controller.admin;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.model.AnoSysLog;
import com.fast.base.security.StringEncrypt;
import com.fast.base.util.DateUtils;
import com.fast.base.util.LogUtils;
import com.fast.base.util.StringUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.base.web.BaseController;
import com.fast.common.userCache.AdminCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.dto.TodoListCountDTO;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.Group;
import com.fast.user.model.admin.dto.MenuDTO;
import com.fast.user.model.dept.Department;
import com.fast.user.service.admin.AdminUserService;
import com.fast.user.service.admin.PermissionService;
import com.fast.user.web.form.web.AdminEditForm;
import com.fast.user.web.form.web.AdminForm;

/**
 * ClassName:AdminUserController <br/>
 * 用途: 管理员业务控制类 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @author lushuifa242
 */
@Controller
@RequestMapping("/adminUser")
public class AdminUserController extends BaseController{
    

	@Resource(name="adminUserService")
	private AdminUserService adminUserService;
	
	@Resource(name="permissionService")
	private PermissionService permissionService;
	
	/**
	 * 得到部门下拉列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getAdminUserList4comboBox.do")
	public List<AdminUser> getMemCompanyList4comboBox(String parentUUID){
		List<AdminUser> adminList =  this.adminUserService.listAdminUser(" where userName<>'kaifa'");
	    return adminList;
	}

	
	/**
	 * 查看待办事项
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/queryTodoListCount.do",method = RequestMethod.POST)
	public ResponseData queryTodoListCount() {
		ResponseData responseData = new ResponseData();
		try {
			int adminId = AdminCacheUtils.getLoginAdminUser().getId();
			String adminUUID = AdminCacheUtils.getLoginAdminUser().getUuid();
			TodoListCountDTO todoListCountDTO = this.adminUserService.queryTodoListCount(adminId,adminUUID);
			responseData.setData(todoListCountDTO);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 核查用户名是否存在，主要用于添加用户时应用
	 * @param userName 用户名
	 * @param request 请求对象
	 * @param response 响应对象
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/checkUserName.do",method = RequestMethod.POST)
	public String checkUserName(String userName) throws Exception {
		boolean isExist = this.adminUserService.isExistUser(userName);
		return Boolean.toString(!isExist);
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value="/toMain.do",method = {RequestMethod.POST,RequestMethod.GET})
	@AnoSysLog(actionName="后台登录系统")
	public ModelAndView toMain(){
		ModelAndView mv = new ModelAndView();
		AdminUser curAdminUser = AdminCacheUtils.getLoginAdminUser();
		List<MenuDTO> menuList = this.permissionService.getSystemLeftMenu(curAdminUser.getGroupId());
		mv.addObject("menuList", menuList);
		mv.setViewName("forward:/adminMain/main.jsp");
		return mv;
	}
	
	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @param captcha
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/login.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="后台登录系统")
	public ResponseData login(String username,String password,String captcha){
		LogUtils.info("username:"+username+",password:"+password+"captcha:"+captcha);
		ResponseData responseData = new ResponseData();
		try {
			//核实用户名在数据中是否存在
			boolean isExist = adminUserService.isExistUser(username);
			if(isExist){
				AdminUser adminUser = adminUserService.login(username,password);
				if (adminUser != null) {
					String verificationCode = (String) webUtil.getSessionAttr("verificationCode");
					if(verificationCode.toUpperCase().equals(captcha.toUpperCase())){
						//改变登录次数
						this.adminUserService.updateLoginInfo(adminUser);
						adminUser.setLoginCount(adminUser.getLoginCount()+1);
						responseData.setData(adminUser);
						webUtil.setSessionAttr("adminUser", adminUser);
						Group group = this.adminUserService.getById(Group.class,adminUser.getGroupId());
						Department department = this.adminUserService.query(Department.class," where uuid='"+adminUser.getDeptUUID()+"'");
						webUtil.setSessionAttr("group", group);
						webUtil.setSessionAttr("department", department);
						String cookieV = URLEncoder.encode(JSONObject.toJSONString(adminUser), "UTF-8");
						Cookie cookie = new Cookie("curAdminUser",cookieV);
						String contextPath = webUtil.getRequest().getContextPath();
						cookie.setPath(""+contextPath+"/manage");
						//单位是分钟
						cookie.setMaxAge(60*60*24);
						webUtil.getResponse().addCookie(cookie);
					}else{
						responseData.buildResult(ResponseEnum.CAPTCHA_FAILD);
					}
				} else {
					responseData.buildResult(ResponseEnum.PASSWORD_FAILD);
				}
			}else{
				responseData.buildResult(ResponseEnum.USER_NULL);
			}
		} catch (Exception e) {
			LogUtils.error("login.err.登录异常：", e);
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("logn.responseData:"+responseData.toString());
		return responseData;
	}
	
	
	/**
	 * 用户登录
	 * @param user 用户对象
	 * @param session
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/temp/login.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="后台登录系统")
	public ResponseData login(String username,String password){
		LogUtils.info("username:"+username+",password:"+password);
		ResponseData responseData = new ResponseData();
		try {
			//核实用户名在数据中是否存在
			boolean isExist = adminUserService.isExistUser(username);
			if(isExist){
				AdminUser adminUser = adminUserService.login(username,StringEncrypt.SHA256(password));
				if (null!=adminUser) {
					if(adminUser.getLocked()==1){
						responseData.buildResult(ResponseEnum.USER_IS_LOCKED);
						return responseData;
					}
					//改变登录次数
					this.adminUserService.updateLoginInfo(adminUser);
					adminUser.setLoginCount(adminUser.getLoginCount()+1);
					responseData.setData(adminUser);
					webUtil.setSessionAttr("adminUser", adminUser);
					Group group = this.adminUserService.getById(Group.class,adminUser.getGroupId());
					//Department department = this.adminUserService.query(Department.class," where uuid='"+adminUser.getDeptUUID()+"'");
					webUtil.setSessionAttr("group", group);
					String cookieV = URLEncoder.encode(JSONObject.toJSONString(adminUser), "UTF-8");
					Cookie cookie = new Cookie("curAdminUser",cookieV);
					String contextPath = webUtil.getRequest().getContextPath();
					cookie.setPath(""+contextPath+"/manage");
					//单位是分钟
					cookie.setMaxAge(60*60*24);
					webUtil.getResponse().addCookie(cookie);
				} else {
					responseData.buildResult(ResponseEnum.PASSWORD_FAILD);
				}
			}else{
				responseData.buildResult(ResponseEnum.USER_NULL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("logn.responseData:"+responseData.toString());
		return responseData;
	}
	
	/**
	 * 编辑[AdminUser]信息
	 * @param AdminUser
	 * @return
	 */
	@AnoSysLog(actionName="添加编辑管理员")
	@ResponseBody
	@RequestMapping(value="/editAdmin.do",method = RequestMethod.POST)
	public ResponseData editAdmin(AdminEditForm adminEditForm){
		LogUtils.info("eidtAdmin is comming!");
		ResponseData responseData = new ResponseData();
		//获取登录用户
		AdminUser adminUser = new AdminUser();
		try {
			//获取用户填写的信息
			BeanUtils.copyProperties(adminUser, adminEditForm);
			//处理生日
			if(StringUtils.isNotEmpty(adminEditForm.getAdminBirthday())){
				adminUser.setBirthday(DateUtils.parse(adminEditForm.getAdminBirthday()));
			}
			
			if(adminUser.getId()<1){
				UserRequestUtils.bindCreaterInfo(adminUser);
			}
			
			UserRequestUtils.bindEditorInfo(adminUser);
			responseData = this.adminUserService.saveOrUpdateAdminUser(adminUser);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除管理信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delAdminUserById.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="删除管理员")
	public ResponseData delAdminUserById(int id) {
		LogUtils.info("delAdminUser is comming!");
		ResponseData responseData = new ResponseData();
		AdminUser adminUser = adminUserService.getById(AdminUser.class, id);
		try {
			if(AdminCacheUtils.getLoginAdminUser().getUserName().equals(adminUser.getUserName())){
				responseData.buildResult(ResponseEnum.DID_NOT_DELSELF);
			}else{
				adminUserService.remove(adminUser);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("删除管理员异常delAdminUser err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除多个管理员信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/batchDelAdminUser.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="删除管理员")
	public ResponseData batchDelAdminUser(String ids) {
		LogUtils.info("delAdminUser is comming!");
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = adminUserService.delAdminUser(ids);
			if(!actionFlag){
				responseData.failue();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("删除管理员异常delAdminUser err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 说明: 重置管理员密码 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年11月9日 上午12:00:47 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping(value="/resetPassword.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="重置管理员密码")
	public ResponseData resetPassword(String ids) {
		LogUtils.info("resetPassword ids:"+ids);
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = adminUserService.resetPassword(ids);
			if(!actionFlag){
				responseData.failue();
			}else{
				responseData.setMsg("选中用户密码已重置为8个8,请及时提醒他们登录并及时改新密码！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("resetPassword err",e);
			responseData.failue();
		}
		LogUtils.info("resetPassword responseData:"+responseData);
		return responseData;
	}
	
	/**
	 * 说明: 检测用户是否是默认密码 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年11月9日 上午12:17:21 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping(value="/checkDefaultPassword.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="检测用户是否是默认密码")
	public ResponseData checkDefaultPassword() {
		LogUtils.info("checkDefaultPassword ids is comming!");
		ResponseData responseData = new ResponseData();
		try {
			AdminUser curAdminUser = AdminCacheUtils.getLoginAdminUser();
			String defaultPsd = StringEncrypt.SHA256("88888888");
			if(!StringUtils.equals(defaultPsd, curAdminUser.getPassword())){
				responseData.failue();
				responseData.setMsg("非默认密码！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("checkDefaultPassword err",e);
			responseData.failue();
		}
		LogUtils.info("checkDefaultPassword responseData:"+responseData);
		return responseData;
	}
	
	/**
	 * 用户退出登录
	 * @param user
	 * 用户对象
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/loginOut.out",method = RequestMethod.POST)
	@AnoSysLog(actionName="后台退出系统")
	public ResponseData loginOut(){
		LogUtils.info("loginOut is comming!");
		ResponseData responseData = new ResponseData();
		try {
			AdminUser adminUser = (AdminUser) webUtil.getSessionAttr("adminUser");
			if(adminUser!=null){
				webUtil.removeSessionAttr("adminUser");
				Cookie cookie = new Cookie("curAdminUser", null); 
				cookie.setMaxAge(0);
				cookie.setPath("/manage");
				webUtil.getResponse().addCookie(cookie);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseData;
	}
	
	/**
	 * 分页获取管理员列表
	 * @param adminForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getAdminList.do",method = RequestMethod.POST)
	public Map<String,Object> getAdminListByPage(AdminForm adminForm) {
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<AdminUser> pageView = new PageView<AdminUser>();
		try {
			String curUserName = AdminCacheUtils.getLoginAdminUser().getUserName();
			adminForm.setCurUserName(curUserName);
			pageView = this.adminUserService.getAdminListByPage(adminForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return gridMap;
	}
	
	/**
	 * 获取管理员详情
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/js/getAdminDetail.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="获取管理员详情")
	public ResponseData getAjaxAdminDetail(String id) {
		LogUtils.info("delAdminUser is comming!");
		ResponseData responseData = new ResponseData();
		try {
			AdminUser adminUser = null;
			if(id.length()>10){
				adminUser = adminUserService.query(AdminUser.class, " where uuid='"+id+"'");
			}else{
				adminUser = adminUserService.getById(AdminUser.class,Integer.parseInt(id));
			}
			responseData.setData(adminUser);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("获取管理员详情getAdminDetail err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 获取管理员详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/getAdminDetail.do",method = RequestMethod.POST)
	@AnoSysLog(actionName="获取管理员详情")
	public ModelAndView getAdminDetail(int id,String actionType) {
		ModelAndView mv = new ModelAndView();
		LogUtils.info("getAdminDetail is comming!");
		try {
			AdminUser adminUser = adminUserService.getById(AdminUser.class,id);
			mv.addObject("adminUserInfo", adminUser);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.info("获取管理员详情getAdminDetail err",e);
		}
		if(StringUtils.isEmpty(actionType)){
			actionType = "detail";
		}
		//根据传入的动作类型设置切换页面
		switch (actionType) {
			case "update":
				mv.setViewName("/adminMain/admin/admin-add.jsp");
				break;
			default:
				mv.setViewName("/adminMain/admin/admin-detail.jsp");
				break;
		}
		return mv;
	}
	
	/**
	 * 核对登录情况
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/checkLoginStatus.out",method = RequestMethod.POST)
	public ResponseData checkLoginStatus(){
		ResponseData responseData = new ResponseData();
		try {
			AdminUser adminUser = (AdminUser) webUtil.getSessionAttr("adminUser");
			if(adminUser==null){
				responseData.failue();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseData;
	}
	
	/**
	 * 核查修改密码时输入的密码是否正确
	 * @param oldPassword 旧密码
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/checkOldPassword.do",method=RequestMethod.GET)
	public String checkOldPassword(String oldPassword) throws Exception {
		String userName = AdminCacheUtils.getLoginAdminUser().getUserName();
		boolean isExist = this.adminUserService.existBean(AdminUser.class, " where userName='"+userName+"' and password='"+StringEncrypt.SHA256(oldPassword)+"'");
		return Boolean.toString(isExist);
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updatePassword.do",method = RequestMethod.POST)
	public ResponseData updatePassword(){
		ResponseData responseData = new ResponseData();
		try {
			Map<String,String> paramMap = super.webUtil.bindDataToMap();
			String newPassword = webUtil.getString("newPassword");
			String oldPassword = webUtil.getString("oldPassword");
			String userName = AdminCacheUtils.getLoginAdminUser().getUserName();
			paramMap.put("newPassword", newPassword);
			paramMap.put("oldPassword", oldPassword);
			paramMap.put("userName", userName);
			responseData = this.adminUserService.updatePassword(paramMap);
			//更新session
			AdminUser adminUser = this.adminUserService.getAdminUserById(AdminCacheUtils.getLoginAdminUser().getId());
			webUtil.setSessionAttr("adminUser", adminUser);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("updatePassword result:"+responseData.toString());
		return responseData;
	}
	
	/**
	 * 核对用户名是否存在
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/isExistsUserName.out",method = RequestMethod.POST)
	public ResponseData isExistsUserName(String userName){
		ResponseData responseData = new ResponseData();
		try {
			boolean isExists = this.adminUserService.isExistUser(userName);
			if(!isExists){
				responseData.failue();
			}else{
				responseData.buildResult(ResponseEnum.SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
}

